package com.linxs.topcham.application.org.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.kissme.core.orm.Page;
import com.linxs.topcham.application.fnas.FansService;
import com.linxs.topcham.application.fnas.KdtapiService;
import com.linxs.topcham.application.org.AgencyOrgService;
import com.linxs.topcham.domain.fans.Order;
import com.linxs.topcham.domain.org.AgencyOrg;
import com.linxs.topcham.infrastruture.persist.fans.FansRepository;
import com.linxs.topcham.infrastruture.persist.org.AgencyOrgRepository;
import com.linxs.topcham.infrastruture.persist.task.OrderRepository;
import com.linxs.topcham.intefaces.utils.MD5Utils;

@Service
public class AgencyOrgServiceImpl implements AgencyOrgService {

	@Autowired
	private AgencyOrgRepository agencyOrgRepository;
	@Autowired
	private FansRepository fansRepository;
	@Autowired
	private KdtapiService apiService;
	@Autowired
	private FansService fansService;
	@Autowired
	private OrderRepository orderRepository;

	@Override
	public AgencyOrg createAgencyOrg(AgencyOrg org) {
		org.setPassword(new MD5Utils().generateMD5(org.getPassword()));
		org.setStatus("1");
		agencyOrgRepository.save(org);

		return null;
	}

	@Override
	public AgencyOrg updateAgencyOrg(AgencyOrg org) {
		agencyOrgRepository.update(org);
		return null;
	}

	@Override
	public AgencyOrg resetAgencyOrgPassword(AgencyOrg org) {
		agencyOrgRepository.resetPassword(org);
		return null;
	}

	@Override
	public Page<AgencyOrg> queryPage(Page<AgencyOrg> page) {
		page = agencyOrgRepository.queryPage(page);

		List<AgencyOrg> result = Lists.newArrayList();

		for (AgencyOrg org : page.getResult()) {
			int fansCount = fansRepository.countFansWithOrg(org.getId());
			// BigDecimal unitPrice = new BigDecimal(100.00); //增员费用，一人100块
			BigDecimal unitPrice = new BigDecimal(0.00);
			BigDecimal number = new BigDecimal(fansCount);

			org.setAddPersonMoney(unitPrice.multiply(number).doubleValue());
			result.add(org);
		}
		page.setResult(result);
		return page;
	}

	@Override
	public void relevanceFans(List<String> ids, long id) {
		// TODO Auto-generated method stub

	}

	@Override
	public AgencyOrg loadAgencyOrgInfo(long id) {
		return agencyOrgRepository.get(id);
	}

	@Override
	public boolean isExistsAccount(String account) {
		AgencyOrg org = agencyOrgRepository.findAgencyOrgByAccount(account);
		if (null == org) {
			return false;
		}
		return true;
	}

	@Override
	public List<AgencyOrg> query() {
		return agencyOrgRepository.query();
	}

	@Override
	public AgencyOrg getByAccount(String username) {
		return agencyOrgRepository.getByAccount(username);
	}

	@Override
	public AgencyOrg get(String id) {
		try {
			
			return agencyOrgRepository.get(Long.valueOf(id));
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public void delete(long id) {
		AgencyOrg org = get(String.valueOf(id));
		org.setStatus("0");
		agencyOrgRepository.update(org);
	}

	@Override
	public List<AgencyOrg> queryCurrentMonth() {

		try {

			String recordTime = new SimpleDateFormat("yyyy-MM").format(new Date());

//			// 已签收的订单
//			List<Order> ensureOrders = apiService.queryThisMonthOrders("TRADE_BUYER_SIGNED");
//			// 退款的订单
//			List<Order> returnOrders = apiService.queryThisMonthOrders("TRADE_CLOSED");
//
//			if (!returnOrders.isEmpty()) {
//				ensureOrders.addAll(returnOrders);
//			}
//
//			for (Order order : ensureOrders) {
//				AgencyOrg org = null;
//				if("0".equals(order.getWeixinUserId())) {
//					org = agencyOrgRepository.queryOrgByFansNick(new String(order.getFansNick().getBytes(), "GBK"));
//				} else {
//					org = agencyOrgRepository.queryOrgByFansUserId(order.getWeixinUserId());
//					
//				}
//				
////				“全国地区” 5%、“城市名” 5%， 默认为3%
//				if (null != org) {
//					if (order.getAddress().indexOf(org.getAreas()) != -1 || "全国地区".equals(org.getAreas())) {
//						order.setBase("0.05");
//						order.setCommission(new BigDecimal("0.05").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
//								.setScale(2, BigDecimal.ROUND_DOWN));
//					} else {
//						order.setBase("0.03");
//						order.setCommission(new BigDecimal("0.03").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
//								.setScale(2, BigDecimal.ROUND_DOWN));
//					}
//					order.setOrgId(org.getId());
//				} else {
//					order.setBase("0.03");
//					order.setCommission(new BigDecimal("0.03").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
//							.setScale(2, BigDecimal.ROUND_DOWN));
//
//				}
//				if ("TRADE_CLOSED".equals(order.getStatus())) {
//					order.setPaymentCommission(new BigDecimal("0.0").setScale(2, BigDecimal.ROUND_DOWN));
//				} else {
//					order.setPaymentCommission(order.getPayment());
//				}
//				order.setRecordTime(recordTime);
//				
//				try {
//					orderRepository.saveOrderMonthRecord(order);
//				} catch (Exception e) {
//					order.setFansNick(new String(order.getFansNick().getBytes(), "GBK")); 
//					orderRepository.saveOrderMonthRecord(order);
//				}
//
//			}

			// 计算增员费用及销售提成
			List<AgencyOrg> ors = agencyOrgRepository.query();
			List<AgencyOrg> result = Lists.newArrayList();

			for (AgencyOrg org : ors) {

				int fansCount = fansRepository.countFansWithOrg(org.getId());
				// BigDecimal unitPrice = new BigDecimal(100.00); //增员费用，一人100块
				BigDecimal unitPrice = new BigDecimal(0.00);
				BigDecimal number = new BigDecimal(fansCount);

				org.setAddPersonMoney(unitPrice.multiply(number).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());

//				List<Order> orders = orderRepository.queryThisMonthOrders(org.getId(), recordTime);
//				BigDecimal commissions = new BigDecimal("0.0").setScale(2, BigDecimal.ROUND_DOWN);

//				List<Fans> fanss = fansService.queryMyFans(org.getAccount());

//				for (Fans fans : fanss) {
//					for (Order order : orders) {
//						if (fans.getUserId().equals(order.getWeixinUserId())) {
//							commissions = commissions.add(order.getCommission());
//						}
//					}
//				}
//				org.setSalesCommissions(commissions.setScale(2, BigDecimal.ROUND_DOWN));

				result.add(org);

			}

			return result;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<AgencyOrg> queryHaveTagsOrgs() {
		return agencyOrgRepository.queryHaveTagsOrgs();
	}

	@Override
	public AgencyOrg queryOrgByFansUserId(String weixinUserId) {
		return agencyOrgRepository.queryOrgByFansUserId(weixinUserId);
	}

	@Override
	public List<AgencyOrg> queryCurrentMonthFormPersiterData() {
		List<Order> currentMonthOrders = orderRepository.queryCurrentMonthPersiterData();
		return null;
	}

}
